package com.tang4j.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tang4j.core.model.ResponseModel;
import com.tang4j.core.model.easyui.TreeGrid;
import com.tang4j.core.model.factory.ResponseModelFactory;
import com.tang4j.core.service.impl.AbstractServiceImpl;
import com.tang4j.mapper.ThSysNavigationMapper;
import com.tang4j.model.ThSysNavigation;
import com.tang4j.model.factory.NavFactory;
import com.tang4j.service.ThSysNavigationService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author saber
 * @since 2019-11-18
 */
@Service
public class ThSysNavigationServiceImpl extends AbstractServiceImpl<ThSysNavigationMapper, ThSysNavigation> implements ThSysNavigationService {

    /**
     * 获取菜单树形结构
     *
     * @return ResponseModel
     */
    @Override
    public ResponseModel getMenuTree() {
        QueryWrapper<ThSysNavigation> wrapper = new QueryWrapper<>();
        List<ThSysNavigation> navList = this.queryList(wrapper);
        List<TreeGrid> tree = NavFactory.createTree(navList);
        //按照父code 分组
        Map<String, List<TreeGrid>> navMap = tree.stream().collect(Collectors.groupingBy(TreeGrid::getPCode));
        //bar菜单
        List<TreeGrid> barList = navMap.get("bar");
        barList.forEach(bar -> {
            //设置bar菜单的子菜单nav菜单
            bar.setChildren(navMap.get(bar.getCode()));
            List<TreeGrid> barChildren = bar.getChildren();
            if (barChildren != null && barChildren.size() != 0) {
                barChildren.forEach(barChild -> {
                    //设置nav的子菜单
                    barChild.setChildren(navMap.get(barChild.getCode()));
                    List<TreeGrid> navChildren = barChild.getChildren();
                    if (navChildren != null && navChildren.size() != 0) {
                        //设置nav的子菜单的子菜单
                        navChildren.forEach(navChild -> navChild.setChildren(navMap.get(navChild.getCode())));
                    }
                });
            }
        });
        return ResponseModelFactory.OKWithData(barList);
    }

}
